<?php
/**
 * media management 媒体管理，包含了对以下两个地址的管理APP_PATH(项目目录)和UPLOAD_PATH（上传目录）
 *
 *   文件：查看、下载、重命名、移动到、复制到、删除、zip的解压
 * 文件夹：移动到、复制到、删除，创建
 *
 */
class pMediaAction extends pBaseAction{

    private $homes=array('APP'=>APP_PATH,'UPLOAD'=>UPLOAD_PATH);
    private $root;
    private $subdir;
    private $filename;  /*要操作的文件名称或者目录名称*/

    public function _initialize(){
        $this->setPath();
    }

    public function index(){
        $files=$this->getSeparateSubFiles($this->homes[$this->root].$this->subdir);
        $this->assign('folders',$files['folders']);
        $this->assign('files',$files['files']);
        $this->assign('rootName',L($this->root));
        $this->assign('root',$this->root);
        $this->assign('subdir',$this->subdir);
        $this->display();
    }

    /**
     * 删除文件或目录
     */
    public function removal(){/*{{{*/
        $filename = array_key_exists('filename',$_POST) ? $_POST['filename'] : false;
        if($filename===false) $this->ajaxReturn(null,null,0);
        $file=$this->homes[$this->root].$this->subdir.$filename;

        $file=(IS_WIN)?auto_charset($file,'utf-8','gbk'):$file;

        if( (is_file($file) && @unlink($file)) || (is_dir($file) && @rmdir($file)) ){
            $this->ajaxReturn(null,null,1);
        }

        $this->ajaxReturn(null,null,0);
    }/*}}}*/

    /**
     * 创建目录
     */
    public function createDirectory(){

        if($this->filename === null) $this->ajaxReturn(null,null,0);

        //检测目录名是否包含非法字符
        if(!$this->checkFilename($this->filename)){
            $this->ajaxReturn(L('invalid_filename'),null,0);
        }

        $filename = $this->homes[$this->root].$this->subdir.$this->filename;
        if(@mkdir($filename,0755)){
            $ret = array();
            $ret['mtime'] = datetime(filemtime($filename));
            $this->ajaxReturn($ret,null,1);
        }

        $this->ajaxReturn(L('create_directory_fail'),null,0);
    }

    /**
     * 接收上传的文件,fancyUpload
     **/
    public function save(){/*{{{*/
        $return = array();
        require THINK_PATH.'/Lib/ORG/Net/UploadFile.class.php';
        $uploader = new UploadFile();
        $uploader->saveRule = '';
        $uploader->uploadReplace = true;
        $uploader->savePath = $this->homes[$this->root].$this->subdir;
        if($uploader->upload()){
            $item=array_shift($uploader->getUploadFileInfo());
            $return['status'] = '1';
            $return['name'] = $item['savename'];
            $return['size'] = $this->getSuitableFileSize($item['size']);
            $return['mtime'] = datetime(filemtime($item['savepath']));
            $return['ext'] = $item['extension'];
        }else{
            $return['status'] = '0';
            $return['error'] = $uploader->getErrorMsg();
        }
        $this->ajaxReturn($return);
    }/*}}}*/

    private function setPath(){/*{{{*/
        //先获取相对的根目录
        $root=$this->getId('root');
        if(false!==$root && array_key_exists($root,$this->homes) ){
            $this->root=$root;
        }else{
            $this->root='APP';
        }
        //获取要浏览的子目录
        $subdir=array_key_exists('subdir',$_POST) ? $_POST['subdir'] : false;
        $this->subdir=(false===$subdir)?'/':rtrim($subdir,'\\/').'/';
        //获取要操作的文件或者目录名称
        $this->filename = array_key_exists('filename',$_POST) ? $_POST['filename'] : null;
    }/*}}}*/

    /*
     * 返回传入目录下的所有文件，目录在前，文件在后
     */
    private function getSeparateSubFiles($path){/*{{{*/
        $files=new DirectoryIterator($path);
        $ret_folder=array();
        $ret_file=array();
        foreach($files as $file){
            $a = array('isFile'=>true,'fileName'=>$this->convertFileName($file->getFilename()),'lastModified'=>datetime($file->getMTime()));
            if($file->isFile()){
                $a['size']=$this->getSuitableFileSize($file->getSize());
                $a['ext']=substr(strrchr($a['fileName'],'.'),1);
                $ret_file[]=$a;
            }else if($file->isDir()){
                $a['isfile']=false;
                $ret_folder[]=$a;
            }
        }
        return array('folders'=>$ret_folder,'files'=>$ret_file);
    }/*}}}*/

    private function getSubFiles($path){
        $ret=$this->getSeparateSubFiles($path);
        return array_merge($ret['foldesr'],$ret['files']);
    }

    /**
     * 检查文件名的有效性
     */
    private function checkFilename($filename){
        return preg_match('/^[^\\/:\*\?"<>\|]*$/',$filename)==1;
    }

    /**
     * 对文件名进行转码
     */
    private function convertFileName($fielName){
        return (IS_WIN) ? auto_charset($fielName,'gbk','utf-8') : $fielName;
    }

    /**
     * 返回合适的文件大小表示
     */
     private function getSuitableFileSize($size){
         if($size<1024){
             return $size.' B';
         }else if($size<1048576){
             return number_format($size/1024,2).' KB';
         }else{
             return number_format($size/1048576,2).' M';
         }
     }
}
